﻿Imports System.IO

Public Class OperacionesLocales

    Public Const CARACTERES_PROHIBIDOS As String = "./\!·$%&'_~|:*?><"

#Region "Directory operations (Creating, renaming, deleting) - DONE"

    ''' <summary>
    ''' Creates a directory.
    ''' </summary>
    ''' <param name="currentLocalPath">Current local path</param>
    ''' <returns>If created, returns the new path. If an error ocurred, returns the current local path</returns>
    ''' <remarks></remarks>
    Public Function createDirectory(ByVal currentLocalPath As String) As String
        Dim newDirectoryName As String = InputBox("Nombre de la nueva carpeta: ", "Nueva carpeta")
        Dim newDirectoryPath As String = currentLocalPath & "\" & newDirectoryName

        If Not newDirectoryName.Replace(" ", "").Equals("") And Not newDirectoryName.Contains(CARACTERES_PROHIBIDOS) And Not IO.Directory.Exists(newDirectoryPath) Then
            Try
                My.Computer.FileSystem.CreateDirectory(newDirectoryPath)
                Return newDirectoryPath
            Catch ex As Exception
                MessageBox.Show("Error en la creación de la carpeta. Posibles errores:" & vbNewLine & "1. El directorio está protegido." & vbNewLine & "2. No tienes permisos suficientes para la creación de carpetas." & vbNewLine & "Excepción: " & ex.Message, "Atención", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Return currentLocalPath
            End Try
        Else
            Return currentLocalPath
            MessageBox.Show("Error en la creación de la carpeta. Posibles errores:" & vbNewLine & "1. La carpeta ya existe." & vbNewLine & "2. El nombre de la carpeta contiene caracteres no válidos." & vbNewLine & "3. Tienes un retraso mental.", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
    End Function

    ''' <summary>
    ''' Renames a directory.
    ''' </summary>
    ''' <param name="currentLocalPath">Current local path</param>
    ''' <returns>Current local path or "ERROR" if an error ocurred</returns>
    ''' <remarks></remarks>
    Public Function renameDirectory(ByVal currentLocalPath As String) As String
        If currentLocalPath <> "" Then
            Dim newName As String = ""
            Try
                Do
                    newName = InputBox("Introduce un nombre nuevo: ", "Renombrar carpeta")
                Loop Until Not newName.Replace(" ", "").Equals("") And Not newName.Contains(CARACTERES_PROHIBIDOS) And Not IO.Directory.Exists(currentLocalPath & "\" & newName)
                My.Computer.FileSystem.RenameDirectory(currentLocalPath, newName)
                Return obtainPreviousDirectory(currentLocalPath)
            Catch ex As Exception
                MessageBox.Show("Error renombrando de la carpeta. Posibles errores:" & vbNewLine & "1. La carpeta ya existe." & vbNewLine & "2. El nombre de la carpeta contiene caracteres no válidos." & vbNewLine & "3. Tienes un retraso mental.", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
        Return "ERROR"
    End Function

    ''' <summary>
    ''' Deletes a directory and all the content inside.
    ''' </summary>
    ''' <param name="currentLocalPath">Current local path</param>
    ''' <returns>Returns the previous path both successing or failing.</returns>
    ''' <remarks></remarks>
    Public Function deleteDirectory(ByVal currentLocalPath As String) As String
        Try
            MsgBox("¿Está seguro de que desea eliminar el directorio con todo lo que contiene " & currentLocalPath & "?", MsgBoxStyle.OkCancel, "Atención")
            If MsgBoxResult.Ok Then
                My.Computer.FileSystem.DeleteDirectory(currentLocalPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
            End If
            Return obtainPreviousDirectory(currentLocalPath)
        Catch ex As Exception
            MessageBox.Show("Error eliminando la carpeta.", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return obtainPreviousDirectory(currentLocalPath)
        End Try
    End Function
#End Region

#Region "File operations"

    ''' <summary>
    ''' Renames a single file.
    ''' </summary>
    ''' <param name="currentLocalPath">Current local path</param>
    ''' <returns>Current local path in both cases</returns>
    ''' <remarks></remarks>
    Public Function renombrarArchivo(ByVal currentLocalPath As String) As String
        Dim newName As String = ""
        Try
            Dim fileName As String = frmPrincipal.lstArchivos.Items(frmPrincipal.lstArchivos.SelectedIndices(0)).Text
            newName = InputBox("Introduce un nombre nuevo para " & fileName & ": " & vbNewLine & "Recuerda colocar la extensión también.", "Renombrar archivo")
            System.IO.File.Move(currentLocalPath & "\" & fileName, currentLocalPath & "\" & newName)
            Return currentLocalPath
        Catch ex As Exception
            MessageBox.Show("Error renombrando el archivo.")
            Return currentLocalPath
        End Try
    End Function

    ''' <summary>
    ''' Deleting a single file.
    ''' </summary>
    ''' <param name="currentLocalPath">Current local path</param>
    ''' <returns>Current local path in both cases</returns>
    ''' <remarks></remarks>
    Public Function deleteFile(ByVal currentLocalPath As String) As String
        Try
            Dim nombreArchivo As String = frmPrincipal.lstArchivos.Items(frmPrincipal.lstArchivos.SelectedIndices(0)).Text
            MsgBox("¿Está seguro de que desea eliminar el archivo " & nombreArchivo & "?", MsgBoxStyle.OkCancel, "Atención")
            If MsgBoxResult.Ok Then
                System.IO.File.Delete(currentLocalPath & "\" & nombreArchivo)
            End If
            Return currentLocalPath
        Catch ex As Exception
            MessageBox.Show("Error eliminando el archivo.")
            Return currentLocalPath
        End Try
    End Function

    ''' <summary>
    ''' Deleting more than one file.
    ''' </summary>
    ''' <param name="currentLocalPath">Current local path</param>
    ''' <returns>Current local path in both cases</returns>
    ''' <remarks></remarks>
    Public Function deleteMoreThanOneFile(ByVal currentLocalPath As String) As String
        Try
            MsgBox("¿Está seguro de que desea eliminar los archivos seleccionados?", MsgBoxStyle.OkCancel, "Atención")
            If MsgBoxResult.Ok Then
                For Each j In frmPrincipal.lstArchivos.SelectedIndices
                    System.IO.File.Delete(currentLocalPath & "\" & frmPrincipal.lstArchivos.Items(j).Text)
                Next
            End If
            Return currentLocalPath
        Catch ex As Exception
            MessageBox.Show("Error eliminando los archivos.")
            Return currentLocalPath
        End Try
    End Function
#End Region

#Region "Methods"

    ''' <summary>
    ''' Obtains the full path of the previous directory used.
    ''' </summary>
    ''' <param name="currentDirectory">Current path</param>
    ''' <returns>Full path of the previous directory used.</returns>
    ''' <remarks></remarks>
    Public Function obtainPreviousDirectory(ByVal currentDirectory As String) As String
        Try
            If IO.Directory.Exists(currentDirectory) Then
                Dim previousDirectory = IO.Directory.GetParent(currentDirectory)
                Return previousDirectory.FullName
            End If
            Return "ERROR"
        Catch ex As Exception
            Return "ERROR"
        End Try
    End Function
#End Region
End Class
